package com.atguigu.gulimall.utils;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Objects;

@Slf4j
public class IndonesiaHeaderFooter extends PdfPageEventHelper {
    private PdfTemplate total; //pdf模板

    private BaseFont bfChinese; //中文字体

    private BaseFont bfEnglish;  //英文字体

    private String langFlag = "E"; //语言版本标志，E：英文，C：中文

    private String versionCode; //版本编号

    private String bfmonth;

    private Integer size;//页眉页脚字体大小

    public IndonesiaHeaderFooter(PdfTemplate total, BaseFont bfChinese, BaseFont bfEnglish, String bfmonth) {
        this.total = total;
        this.bfChinese = bfChinese;
        this.bfEnglish = bfEnglish;
        this.bfmonth = bfmonth;
    }

    public IndonesiaHeaderFooter(BaseFont bfChinese, BaseFont bfEnglish, String bfmonth, Integer size, String versionCode) {
        this.bfChinese = bfChinese;
        this.bfEnglish = bfEnglish;
        this.bfmonth = bfmonth;
        this.size = size;
        this.versionCode = versionCode;
    }

    public IndonesiaHeaderFooter(BaseFont bfChinese, BaseFont bfEnglish, String bfmonth, Integer size, String langFlag, String versionCode) {
        this.bfChinese = bfChinese;
        this.bfEnglish = bfEnglish;
        this.bfmonth = bfmonth;
        this.size = size;
        this.langFlag = langFlag;
        this.versionCode = versionCode;
    }

    @Override
    public void onOpenDocument(PdfWriter writer, Document document) {
        super.onOpenDocument(writer, document);
    }

    @SneakyThrows
    @Override
    public void onStartPage(PdfWriter writer, Document document) {
        //super.onStartPage(writer, document);
        /*Rectangle tRectangle = new Rectangle(PageSize.A4); // 页面大小
        tRectangle.setBorder(1220);// 边框
        tRectangle.setBorderColor(BaseColor.BLUE);// 边框颜色
        tRectangle.setBorderWidth(244.2f);// 边框宽度*/
        //writer.
    }

    @SneakyThrows
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();// 得到层
        cb.saveState();
        //表頭
        cb.beginText();
        setImg(writer, null, 70, 36, 20, 795);
        cb.endText();
        // 开始
        cb.beginText();
        cb.setColorFill(BaseColor.GRAY);
        //判断语言版本
        if ("E".equals(langFlag)){
            cb.setFontAndSize(bfEnglish, size);
            float x = document.top(-10);// 位置
            float y = document.bottom(-20);
//            cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, versionCode, document.right(25), document.top(-10), 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "Page " + writer.getPageNumber() + " of "+"3", document.right()-50, y, 0);
            // 右

            // 在页脚显示换行文本
//            Paragraph footer = new Paragraph("ARL \n International");
//            footer.setAlignment(Element.ALIGN_CENTER);
//            footer.add(Chunk.NEWLINE);
//            footer.add("International");
//            footer.setSpacingAfter(10); // 设置段后间距
//            ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, new Phrase(footer), 50, y, 0);

            // 第一行文本
            Phrase phrase1 = new Phrase(10, "ARL International Limited", new Font(Font.FontFamily.HELVETICA, 8));
            ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, phrase1, 50, document.bottom() - 30, 0);

            // 第二行文本
            Phrase phrase2 = new Phrase(10, "Labuan F.T., Malaysia ", new Font(Font.FontFamily.HELVETICA, 8));
            ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, phrase2, 50, document.bottom() - 40, 0);

            // 第三行文本
            Phrase phrase3 = new Phrase(10, "Co. No. LL04581 License No. BS200546", new Font(Font.FontFamily.HELVETICA, 8));
            ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, phrase3, 50, document.bottom() - 50, 0);


//            cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "ARL \n International \n Limited", 50, y, 0);
//            cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "ARL \n International \n Limited", 50, -30, 0);
        }else{  //默认中文
            cb.setFontAndSize(bfChinese, size);
            float x = document.top(-10);// 位置
            float y = document.bottom(-12);
//            cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, versionCode, document.right(35), document.top(-2), 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "第" + writer.getPageNumber() + "頁，共"+"3"+"頁", document.right()-20, y, 0);
            // 右
            cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, bfmonth, (document.right() + document.left()) / 2, y, 0);
        }
        cb.endText();
        cb.restoreState();

        //大边框
        // A4 595×842
//        Rectangle pageRect = new Rectangle(15,15,580,827);  //文档矩形
//        pageRect.setBorderWidthTop(0.5F);
//        pageRect.setBorderWidthLeft(0.5F);
//        pageRect.setBorderWidthBottom(0.5F);
//        pageRect.setBorderWidthRight(0.5F);
//        pageRect.setBorderColor(BaseColor.BLACK);
//        pageRect.setUseVariableBorders(true);
//        cb.rectangle(pageRect);
    }

    @Override
    public void onCloseDocument(PdfWriter writer, Document document) {
        super.onCloseDocument(writer, document);
    }


    public static void setImg(PdfWriter writer, String path, float fitWidth, float fitHeight, float absoluteX, float absoluteY) {
        try {
            Image image = getImageFromInputStream(Objects.requireNonNull(MyHeaderFooter.class.getClassLoader().getResourceAsStream("images/logo.png")));
            image.setAlignment(Image.MIDDLE);
            image.scaleToFit(fitWidth, fitHeight);
            image.setAbsolutePosition(absoluteX, absoluteY);
            writer.getDirectContent().addImage(image);
        } catch (Exception e) {
            log.error("error", e);
            log.error("[ERROR] Set Img : img file does not exist.");
        }
    }


    /**
     *
     * @param inputStream
     * @return 将InputStream转化为Image
     * @throws Exception
     */
    public static Image getImageFromInputStream(InputStream inputStream) throws Exception {
        int n;
        byte[] buffer = new byte[4096];
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        while (-1 != (n = inputStream.read(buffer))) {
            output.write(buffer, 0, n);
        }
        Image image = Image.getInstance(output.toByteArray());
        return image;
    }
}
